package com.xzl.xep.common.utils;


import java.util.HashMap;
import java.util.Map.Entry;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;






/**
 * 
 * 
 * Title:
 * 
 * Description:
 * 
 * Copyright: Copyright (c) 2008
 * 
 * @author haoxz11
 * @created Mar 7, 2008 11:56:34 AM
 * @version $Id: CookieUtil.java,v 1.1 2013/10/23 03:26:18 haoxz11 Exp $
 */
public class CookieUtil { 
	private static Log log = LogFactory.getLog(CookieUtil.class);

	public static final Long TIME_MAX = 99999999L;
	public static final Long TIME_TODAY = 86400L;
	public static final Long TIME_CLIENT = -1L;

	
	private HashMap<String,HashMap<String,String>> cookieData=new HashMap<String,HashMap<String,String>>();
	private HttpServletRequest request = null;

	private HttpServletResponse response = null;

	public CookieUtil(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		parseCookie();
	}
	
	/**
	 * 有没有这个key
	 * @param timeType
	 * @param key
	 * @return
	 */
	public boolean hasKey(Long timeType,String key) {
		try{
			return cookieData.get(String.valueOf(timeType)).containsKey(key);
		}catch(Exception e){
			return false;
		}
	}
	
	/**
	 * 取值
	 * @param timeType
	 * @param key
	 * @return
	 */
	public String getValue(Long timeType,String key) {
		try{
			return cookieData.get(String.valueOf(timeType)).get(key);
		}catch(Exception e){
			return null;
		}
	}

	/**
	 * 设值
	 * @param timeType
	 * @param key
	 * @param value
	 */
	public void setValue(Long timeType,String key, Object value) {
		HashMap<String, String> cd = cookieData.get(timeType.toString());
		if (key != null) {
			if (value != null) {
				if(cd==null){
					cookieData.put(String.valueOf(timeType), new HashMap<String, String>());
					cd=cookieData.get(String.valueOf(timeType));
				}
				cd.put(key, value.toString());
			} else {
				if(cd!=null){
					cd.remove(key);
				}
			}
		}
	}
	
	/**
	 * 保存
	 */
	public void save() {
		for(Entry<String,HashMap<String,String>> cookie:cookieData.entrySet()){
			StringBuilder cdString = new StringBuilder();
			for (Entry<String,String> kv:cookie.getValue().entrySet()) {
				if ((kv.getKey() != null) && (kv.getValue() != null)) {
					if(cdString.length()>0){
						cdString.append("&");
					}
					cdString.append(kv.getKey()).append("=").append(kv.getValue());
				}
			}
			if(cdString.length()>0){
				String val = SecurityUtil.encrypt(cdString.toString());
				int age = NumberUtil.parseInt(cookie.getKey());
				if(age<=0){
					age=-1;
				}
				addCookie(String.valueOf(age), val, age);
			}else{
				addCookie(cookie.getKey(), null, 0);
			}
		}
	}
	
	/**
	 * 解析
	 */
	private void parseCookie() {
		Cookie[] cookies = null;
		try {
			cookies = request.getCookies();
		} catch (IllegalArgumentException iae) {
			log.error("", iae);
		}
		if (cookies == null) {
			return;
		}
		for(Cookie cookie:request.getCookies()){
			String tmp=SecurityUtil.decrypt(cookie.getValue());
			if(StringUtil.isNotEmpty(tmp)){
				HashMap<String,String> map=new HashMap<String,String>();
				String[] keyValue = tmp.split("&");
				for (int i = 0; (keyValue != null) && (i < keyValue.length); i++) {
					if (keyValue[i] != null) {
						int offset = keyValue[i].indexOf("=");
						if ((offset > 0) && (offset < (keyValue[i].length() - 1))) {
							map.put(keyValue[i].substring(0, offset), keyValue[i]
									.substring(offset + 1, keyValue[i].length()));
						}
					}
				}
				cookieData.put(cookie.getName(), map);
			}
		}
	}
	
	/**
	 * 保存到cookie
	 * @param name
	 * @param val
	 * @param age
	 */
	private void addCookie(String name, String val, int age) {
		Cookie c = new Cookie(name, val);
		c.setMaxAge(age);
		c.setPath("/");
		response.addCookie(c);
	}
}